package com.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.system.entity.SysMenu;
import com.system.entity.SysMenuBtn;
import com.system.entity.SysRoleRel;
import com.system.entity.SysRoleRel.RelType;
import com.system.page.SysMenuModel;
import com.system.service.SysMenuBtnService;
import com.system.service.SysMenuService;
import com.system.service.SysRoleRelService;
import common.base.entity.BaseEntity.DELETED;
import common.base.entity.TreeNode;
import common.base.util.TreeUtil;
import common.base.web.BaseAction;

 
@Controller
@RequestMapping("/sysMenu") 
public class SysMenuAction extends BaseAction{
	
	private final static Logger log= Logger.getLogger(SysMenuAction.class);
	
	// Servrice start
	@Autowired(required=false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private SysMenuService<SysMenu> sysMenuService; 
	
	@Autowired
	private SysMenuBtnService<SysMenuBtn> sysMenuBtnService;
	
	@Autowired(required=false) 
	private SysRoleRelService<SysRoleRel> sysRoleRelService;
	
	/**
	 * ilook 首页
	 * @param url
	 * @param classifyId
	 * @return
	 */
	@RequestMapping("/menu")
	public ModelAndView menu(SysMenuModel model,HttpServletRequest request) throws Exception{
		Map<String,Object>  context = getRootMap();
		model.setDeleted(DELETED.NO.key);
		List<SysMenu> dataList = sysMenuService.queryByList(model);
		//设置页面数据
		context.put("dataList", dataList);
		return forword("sys/sysMenu",context); 
	}
	
	/**
	 * 顶级菜单 json 
	 * @param menuId 此菜单id不查询，可以为空
	 * @param response
	 * @return 
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/rootMenuJson") 
	public List<SysMenu> rootMenu(Integer menuId) throws Exception{
		List<SysMenu> dataList = sysMenuService.getRootMenu(menuId);
		if(dataList==null){
			dataList = new ArrayList<SysMenu>();
		}
		return dataList;
	}
	
	/**
	 * json 列表页面
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/dataList") 
	public Map<String, Object> dataList(SysMenuModel model) throws Exception{
		List<SysMenu> dataList = sysMenuService.queryByList(model);
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("total",model.getPager().getRowCount());
		jsonMap.put("rows", dataList);
		return jsonMap;
	}
	
	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/save")
	public Map<String,Object> save(SysMenu bean,HttpServletRequest request) throws Exception{
		//设置菜单按钮数据
		List<SysMenuBtn> btns = getReqBtns(request);
		bean.setBtns(btns);
		if(bean.getId() == null){
			bean.setDeleted(DELETED.NO.key);
			sysMenuService.add(bean);
		}else{
			sysMenuService.update(bean);
		}
		return sendSuccessMessage("保存成功~");
	}
	
	@ResponseBody
	@RequestMapping("/getId")
	public Map<String,Object> getId(Integer id,HttpServletRequest request) throws Exception{
		Map<String,Object>  context = new HashMap<String,Object>();
		SysMenu bean  = sysMenuService.queryById(id);
		if(bean  == null){
			return sendFailureMessage("没有找到对应的记录!");
		}
		List<SysMenuBtn> btns = sysMenuBtnService.queryByMenuid(id);
		bean.setBtns(btns);
		context.put(SUCCESS, true);
		context.put("data", bean);
		return context;
	}
	
	@ResponseBody
	@RequestMapping("/delete")
	public Map<String,Object> delete(Integer[] id,HttpServletRequest request) throws Exception{
		if(id != null && id.length > 0){
			sysMenuService.delete(id);
			return sendSuccessMessage("删除成功");
		}else{
			return sendFailureMessage("未选中记录");
		}
	}
	
	@ResponseBody
	@RequestMapping("/getMenuTree2")
	public Map<String,Object> getMenuTree2(Integer id,HttpServletRequest request) throws Exception{
		Map<String,Object> context = new HashMap<String,Object>();
		List<Map<String, Object>> menuList = sysMenuService.getAllMenu();
		List<Map<String, Object>> btnList = sysMenuService.getAllBtn();
		List<Map<String, Object>> allMenuList = new ArrayList<Map<String,Object>>();
		List<String> parentIdList = new ArrayList<String>();
		for(int i=0;i<menuList.size();i++){
			Map<String, Object> map1 = new HashMap<String, Object>();
			Map<String, Object> map2 = menuList.get(i);
			String id1 = map2.get("id").toString();
			parentIdList.add(id1);
			String name = map2.get("name").toString();
			if(map2.containsKey("parentId")){
				String parentId = map2.get("parentId").toString();
				map1.put("pId", parentId);
			}else{
				map1.put("pId", 0);
			}
			map1.put("id", id1);
			map1.put("name", name);
			map1.put("open", false);
			allMenuList.add(map1);
		}
		for(int i=0;i<btnList.size();i++){
			Map<String, Object> map1 = new HashMap<String, Object>();
			Map<String, Object> map2 = btnList.get(i);
			String id1 = map2.get("id").toString();
			String name = map2.get("name").toString();
			if(map2.containsKey("parentId")){
				String parentId = map2.get("parentId").toString();
				if(parentIdList.contains(parentId)){
					map1.put("pId", parentId);
					map1.put("id", id1+"c");
					map1.put("name", name);
					map1.put("open", true);
					allMenuList.add(map1);
				}
			}else{
				map1.put("pId", 0);
				map1.put("id", id1+"c");
				map1.put("name", name);
				map1.put("open", true);
				allMenuList.add(map1);
			}
		}
		context.put("menuTree", allMenuList);
		return context;
	}
	
	
	/**
	 * 修改角色时获取菜单树
	 * @param id
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getMenuTree3")
	public Map<String,Object> getMenuTree3(Integer id,HttpServletRequest request) throws Exception{
		Map<String,Object> context = new HashMap<String,Object>();
		List<Map<String, Object>> menuList = sysMenuService.getAllMenu();
		List<Map<String, Object>> btnList = sysMenuService.getAllBtn();
		List<Map<String, Object>> allMenuList = new ArrayList<Map<String,Object>>();
		
		//获取权限关联的菜单
		String[] menuIds = null;
		List<SysMenu> menuList1 =  sysMenuService.getMenuByRoleId(id);
		if(menuList != null){
			menuIds = new String[menuList1.size()];
			int i = 0;
			for(SysMenu item : menuList1){
				menuIds[i] = item.getId().toString();
				i++;
			}
		}
		//获取权限下关联的按钮
		String[] btnIds = null;
		List<SysRoleRel>  btnList1 =sysRoleRelService.queryByRoleId(id, RelType.BTN.key);
		if(btnList != null){
			btnIds = new String[btnList1.size()];
			int i = 0;
			for(SysRoleRel item : btnList1){
				btnIds[i] = item.getObjId().toString();
				i++;
			}
		}
		//将菜单和按钮数组转化为list
		List<String> mList = new ArrayList<String>();
		List<String> bList = new ArrayList<String>();
		
		for(int i=0;i<menuIds.length;i++){
			mList.add(menuIds[i]);
		}
		
		for(int i=0;i<btnIds.length;i++){
			bList.add(btnIds[i]);
		}
		
		List<String> parentIdList = new ArrayList<String>();
		for(int i=0;i<menuList.size();i++){
			Map<String, Object> map1 = new HashMap<String, Object>();
			Map<String, Object> map2 = menuList.get(i);
			String id1 = map2.get("id").toString();
			parentIdList.add(id1);
			String name = map2.get("name").toString();
			if(map2.containsKey("parentId")){
				String parentId = map2.get("parentId").toString();
				map1.put("pId", parentId);
			}else{
				map1.put("pId", 0);
			}
			
			for(int j=0;j<mList.size();j++){
				if(mList.contains(id1)){
					map1.put("checked", true);
				}
			}
			
			map1.put("open", true);
			map1.put("id", id1);
			map1.put("name", name);
			allMenuList.add(map1);
		}
		for(int i=0;i<btnList.size();i++){
			Map<String, Object> map1 = new HashMap<String, Object>();
			Map<String, Object> map2 = btnList.get(i);
			String id1 = map2.get("id").toString();
			String name = map2.get("name").toString();
			if(map2.containsKey("parentId")){
				String parentId = map2.get("parentId").toString();
				if(parentIdList.contains(parentId)){
					map1.put("pId", parentId);
					map1.put("id", id1+"c");
					map1.put("name", name);
					for(int j=0;j<bList.size();j++){
						if(bList.contains(id1)){
							map1.put("checked", true);
							map1.put("open", true);
						}
					}
					allMenuList.add(map1);
				}
			}else{
				map1.put("pId", 0);
				map1.put("id", id1+"c");
				map1.put("name", name);
				for(int j=0;j<bList.size();j++){
					if(bList.contains(id1)){
						map1.put("checked", true);
						map1.put("open", true);
					}
				}
				allMenuList.add(map1);
			}
		}
		context.put("menuTree", allMenuList);
		return context;
	}
	
	
	/**
	 * 构建树形菜单
	 * @return
	 */
	public List<TreeNode> treeMenu(){
		List<SysMenu> rootMenus = sysMenuService.getRootMenu(null);//根节点
		List<SysMenu> childMenus = sysMenuService.getChildMenu();//子节点
		List<SysMenuBtn> childBtns = sysMenuBtnService.queryByAll();
		TreeUtil util = new TreeUtil(rootMenus,childMenus,childBtns);
		return util.getTreeNode();
	}
	
	/**
	 * 获取请求的菜单按钮数据
	 * @param request
	 * @return
	 */
	public List<SysMenuBtn> getReqBtns(HttpServletRequest request){
		List<SysMenuBtn> btnList= new ArrayList<SysMenuBtn>();
		String[] btnId  = request.getParameterValues("btnId");
		String[] btnName  = request.getParameterValues("btnName");
		String[] btnType  = request.getParameterValues("btnType");
		String[] actionUrls  = request.getParameterValues("actionUrls");
		String[] deleteFlag  = request.getParameterValues("deleteFlag");
		if(btnId  == null || btnId.length < 1){
			return null;
		}
		
		for (int i = 0; i < btnId.length; i++) {
			if(StringUtils.isNotBlank(btnName[i]) && StringUtils.isNotBlank(btnType[i])){
				SysMenuBtn btn = new SysMenuBtn();
				if(StringUtils.isNotBlank(btnId[i]) && NumberUtils.isNumber(btnId[i])){
					btn.setId(NumberUtils.toInt(btnId[i]));
				}
				btn.setBtnName(btnName[i]);
				btn.setBtnType(btnType[i]);
				btn.setActionUrls(actionUrls[i]);
				btn.setDeleteFlag(deleteFlag[i]);
				btnList.add(btn);
			}
		}
		return btnList;
	}
}